<template>
  <div>
    <div>
      <FormPanel
        ref="formPanel"
        :list="formList"
        :cols="2"
        :formType="type"
        labelWidth="110"
        :isSubmitBtn="false"
        @formChange="formChangeHandle"
      />
      <!-- <el-form :model="driveTime" ref="addDriveForm" label-width="110px" :rules="rules">
        <template>
          <el-form-item label="试驾开始时间" prop="driveSAt">
            <el-date-picker
              v-model="driveTime.driveSAt"
              type="datetime"
              placeholder="选择日期时间"
              default-time="23:59:00"
              format="yyyy-MM-dd HH:mm"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="试驾结束时间" prop="driveEAt">
            <el-date-picker
              v-model="driveTime.driveEAt"
              type="datetime"
              placeholder="选择日期时间"
              default-time="23:59:00"
              format="yyyy-MM-dd HH:mm"
            ></el-date-picker>
          </el-form-item>
        </template>
      </el-form> -->
    </div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'center'
      }"
    >
      <el-button @click="closeDialog">取 消</el-button>
      <el-button @click="saveDialog('addDriveForm')"   :loading="saveLoading"    v-if="this.type !='show'" type="primary">保 存</el-button>
    </div>
    <BaseDialog :visible.sync="visible" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SearchName :type="handleType" :rowData="formData" @close="closeHandler" />
    </BaseDialog>
  </div>
</template>

<script>
import {
  getDriveCarInfo,
  getDriveWayInfo,
  addDriveManagement,
  editDriveManagement,
  detailDriveManagement,
  queryPotentialById,
  driveCancel,
  addDriveManagementBq } from '@/api/potenCus/customer/driveManagement';
import { dictionary } from '@/utils/dictMixin';
import SearchName from './searchName';
import { IDNumber, phone, VIN, formatDates } from '@/utils/validate';

export default {
  name: 'DriveModalBq',
  mixins: [dictionary],
  components: {
    SearchName
  },
  props: {
    type: {
      type: String,
      default: 'add'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.saveData = null;
    this.toggleList = [
      {
        type: 'UPLOAD_IMG',
        label: '驾驶证正面',
        fieldName: 'drivingLicenceFront',
        valueType: 'Array',
        rules: [{ required: true, message: '请上传图片', trigger: 'change' }],
        change: val => {
          if (this.dataType === this.typeItems[0].value) {
            this.typeItems[0].pics.drivingLicenceFront = val;
          } else {
            this.typeItems[1].pics.identityCardFront = val;
          }
        },
        upload: {
          actionUrl: '/api/file/oss/upload',
          fixedSize: [5, 3],
          limit: 1,
          isCalcHeight: true
        }
      },
      {
        type: 'UPLOAD_IMG',
        label: '驾驶证反面',
        fieldName: 'drivingLicenceBack',
        valueType: 'Array',
        rules: [{ required: true, message: '请上传图片', trigger: 'change' }],
        change: val => {
          if (this.dataType === this.typeItems[0].value) {
            this.typeItems[0].pics.drivingLicenceBack = val;
          } else {
            this.typeItems[1].pics.identityCardBack = val;
          }
        },
        upload: {
          actionUrl: '/api/file/oss/upload',
          fixedSize: [5, 3],
          limit: 1,
          isCalcHeight: true
        }
      }
    ];
    this.typeItems = [
      {
        value: 20261002,
        text: '试驾',
        pics: {
          drivingLicenceFront: null,
          drivingLicenceBack: null
        }
      },
      {
        value: 20261001,
        text: '试乘',
        pics: {
          identityCardFront: null,
          identityCardBack: null
        }
      }
    ];
    this.dataType = this.typeItems[0].value; // 默认试驾

    this.customerNo = ''; // 潜客编号
    return {
      formList: this.createFormList(),
      handleType: '',
      formData: {},
      visible: false,
      dialogTitle: '',
      driveTime: {
        driveSAt: '',
        driveEAt: ''
      },
      rules: {
        actionStatus: [{ required: true, message: '请选择跟进结果', trigger: 'blur' }],
        invalidReason: [{ required: true, message: '请选择无效原因', trigger: 'blur' }]
      },
      conf: { search: '选择试驾客户' },
      saveLoading :false
    };
  },
  created() {
    this.init();
    this.getDriveCarList();
    this.getDriveWayList();
  },
  methods: {
    init() {
      // console.log("rowData222222222",this.rowData)
      // console.log("type",this.type)
      if (this.type === 'add') {
        // this.formList.find(x => x.fieldName === 'driveEAt').offsetRightCols = 1;
        if (JSON.stringify(this.rowData) != '{}') {
          this.formList.forEach(x => {
            x.initialValue = x.fieldName === 'driveType' ? x.initialValue : this.rowData[x.fieldName];
          });
        }
        this.customerNo = this.rowData.customerBusinessId; // 潜客编号
      }
      if (this.type === 'edit' || this.type === 'show') {
        this.recordId = this.rowData.itemId;
        this.getDriveInfo();
        this.formList.forEach(x => {
          // 说明这个字段得是数组
          if (x.valueType === 'Array') {
            x.initialValue = [this.rowData[x.fieldName]];
          } else if (x.fieldName === 'testDriveFileDTOList') {
            x.initialValue = [
              {
                name: this.rowData['drivingDisclaimerName'] || '文件',
                url: this.rowData['drivingDisclaimer']
              }
            ];
          } else {
            x.initialValue = this.rowData[x.fieldName];
          }
        });
      }
      this.typeChangeHandle(this.rowData.driveType);
      this.typeChangeHandle(this.rowData.driveType);
    },
    typeChangeHandle(typeCode) {
      // this.$refs.formPanel.SUBMIT_FORM();
      // console.log(this.saveData)
      if (typeCode === this.typeItems[0].value) {
        this.typeItems[0].pics.drivingLicenceFront = this.rowData['drivingLicenceFront'] ? [this.rowData['drivingLicenceFront']] : this.typeItems[0].pics.drivingLicenceFront;
        this.typeItems[0].pics.drivingLicenceBack = this.rowData['drivingLicenceBack'] ? [this.rowData['drivingLicenceBack']] : this.typeItems[0].pics.drivingLicenceBack;
        this.toggleList[0].label = '驾驶证正面';
        this.toggleList[0].fieldName = 'drivingLicenceFront';
        this.toggleList[1].label = '驾驶证反面';
        this.toggleList[1].fieldName = 'drivingLicenceBack';
        this.toggleList[0].initialValue = this.typeItems[0].pics.drivingLicenceFront;
        this.toggleList[1].initialValue = this.typeItems[0].pics.drivingLicenceBack;
      }
      if (typeCode === this.typeItems[1].value) {
        this.typeItems[1].pics.identityCardFront = this.rowData['identityCardFront'] ? [this.rowData['identityCardFront']] : this.typeItems[1].pics.identityCardFront;
        this.typeItems[1].pics.identityCardBack = this.rowData['identityCardBack'] ? [this.rowData['identityCardBack']] : this.typeItems[1].pics.identityCardBack;
        this.toggleList[0].label = '身份证正面';
        this.toggleList[0].fieldName = 'identityCardFront';
        this.toggleList[1].label = '身份证反面';
        this.toggleList[1].fieldName = 'identityCardBack';
        this.toggleList[0].initialValue = this.typeItems[1].pics.identityCardFront;
        this.toggleList[1].initialValue = this.typeItems[1].pics.identityCardBack;
      }
    },
    createFormList() {
      return [
        {
          type: 'RADIO',
          label: '试驾类型',
          fieldName: 'driveType',
          selfCols: 2,
          placeholder: '请选择',
          initialValue: this.typeItems[0].value,
          itemList: this.typeItems,
          change: val => {
            this.dataType = val;
            this.typeChangeHandle(val);
          },
          rules: [{ required: true, message: '请选择试驾类型', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'potentialCustomerName',
          placeholder: '点击搜索试驾客户',
          initialValue: '',
          readonly: true,
          unitRender: () => {
            return (
              <el-button
                slot="append"
                disabled={JSON.stringify(this.rowData) != '{}' && this.type === 'add'}
                icon="el-icon-search"
                onClick={JSON.stringify(this.rowData) != '{}' && this.type === 'add' ? '' : this.openDriveCancel}
              ></el-button>
            );
          },
          rules: [{ required: true, message: '客户名称不能为空', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '客户手机号',
          fieldName: 'potentialCustomerPhone',
          placeholder: '',
          initialValue: '',
          readonly: true,
          rules: [
            { required: true, message: '客户手机号不能为空', trigger: 'blur' },
            { trigger: 'blur', validator: phone }
          ]
        },
        {
          type: 'INPUT',
          label: '销售顾问',
          fieldName: 'employeeName',
          placeholder: '',
          readonly: true,
          rules: [{ required: true, message: '销售顾问不能为空', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '试驾人名称',
          fieldName: 'customerName',
          placeholder: '请输入',
          rules: [{ required: true, message: '试驾人名称不能为空', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '试驾人手机号',
          fieldName: 'mobile',
          placeholder: '请输入',
          rules: [
            { required: true, message: '手机号不能为空', trigger: 'blur' },
            { trigger: 'blur', validator: phone }
          ]
        },
        {
          type: 'INPUT',
          label: '证件号码',
          fieldName: 'driverCard',
          placeholder: '请输入',
          rules: [
            { required: true, message: '证件号码不能为空', trigger: 'change' },
            { trigger: 'blur', validator: IDNumber }
          ]
        },
        {
          type: 'SELECT',
          label: '试驾车辆',
          fieldName: 'testDriveId',
          placeholder: '请选择',
          itemList: [],
          rules: [{ required: true, message: '试驾车辆不能为空', trigger: 'change' }],
          change: val => {
            this.changeVinSelect(val);
          }
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          disabled: true,
          placeholder: '请输入',
          initialValue: '',
          rules: [{ required: true, message: 'VIN不能为空', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '路线选择',
          fieldName: 'wayId',
          placeholder: '请选择',
          itemList: [],
          rules: [{ required: true, message: '路线不能为空', trigger: 'change' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '试驾里程(KM)',
          fieldName: 'totalMileage',
          placeholder: '试驾里程(KM)',
          rules: [{ required: true, message: '试驾里程不能为空', trigger: 'change' }]
        },
        {
          type: 'DATE',
          label: '试驾开始时间',
          fieldName: 'driveSAt',
          dateType: 'datetime',
          placeholder: '开始时间',
          rules: [{ required: true, message: '请选择开始时间', trigger: 'blur' }]
        },
        {
          type: 'DATE',
          label: '试驾结束时间',
          fieldName: 'driveEAt',
          dateType: 'datetime',
          placeholder: '结束时间',
          rules: [{ required: true, message: '请选择结束时间', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '推荐人姓名',
          fieldName: 'referrerName',
          placeholder: '请输入',
          initialValue: '',
          // rules: [{ required: true, message: 'VIN不能为空', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '推荐人电话',
          maxlength: 11,
          fieldName: 'referrerPhone',
          placeholder: '请输入',
          initialValue: '',
          // rules: [{ required: true, message: 'VIN不能为空', trigger: 'blur' }]
        },
        ...this.toggleList,
        {
          type: 'UPLOAD_FILE',
          label: '试乘试驾责任书',
          selfCols: 2,
          style: { width: '200px' },
          fieldName: 'testDriveFileDTOList',
          placeholder: '试乘试驾责任书...',
          disabled: this.type == 'show' ? true : false,
          rules: [{ required: true, message: '请上传试乘试驾责任书', trigger: 'change' }],
          upload: {
            actionUrl: '/api/file/oss/upload',
            limit: 1
          }
        }
      ];
    },
    formChangeHandle(val) {
      this.saveData = _.cloneDeep(val);
    },
    // 获取试驾明细
    async getDriveInfo() {
      const res = await detailDriveManagement(this.recordId);
      console.log('试驾明细', res);
      if (res.resultCode === 200) {
        this.formList.forEach(x => {
          console.log('x', x);
          if (x.fieldName === 'vin') {
            x.initialValue = res.data[x.fieldName]
          }
          if (x.fieldName === 'wayId') {
            let isHasWayId = x.itemList.some(item => item.value === res.data['wayId']);
            !isHasWayId ? x.itemList.push({ text: res.data['wayName'], value: res.data['wayId'] }) : '';
          }
          if (x.fieldName === 'testDriveId') {
            let isTestDriveId = x.itemList.some(item => item.value === res.data['testDriveId']);
            !isTestDriveId ? x.itemList.push({ text: res.data['carInfoName'], value: res.data['testDriveId'] }) : '';
          }
          if (x.fieldName === 'totalMileage' && res.data.driveRunKm) {
            x.initialValue = res.data.driveRunKm
          }
          if (x.fieldName === 'driveSAt' && res.data.driveSAt) {
            x.initialValue = formatDates(Number(res.data.driveSAt));
          }
          if (x.fieldName === 'driveEAt' && res.data.driveEAt) {
            x.initialValue = formatDates(Number(res.data.driveEAt));
          }
        });
      }
    },
    showHandler() {
      this.dialogTitle = `${this.conf[this.handleType]}`;
      this.visible = true;
    },
    async saveDialog() {
      this.$refs.formPanel.SUBMIT_FORM();
      console.log('this.saveData', this.saveData)
      if (this.saveData !== null) {
        if (this.dataType === this.typeItems[0].value) {
          // 试驾
          if (Array.isArray(this.saveData.drivingLicenceFront) && this.saveData.drivingLicenceFront.length) {
            this.saveData.drivingLicenceFront = this.saveData.drivingLicenceFront[0];
          }
          if (Array.isArray(this.saveData.drivingLicenceBack) && this.saveData.drivingLicenceBack.length) {
            this.saveData.drivingLicenceBack = this.saveData.drivingLicenceBack[0];
          }
          delete this.saveData.identityCardFront;
          delete this.saveData.identityCardBack;
        }
        if (this.dataType === this.typeItems[1].value) {
          // 试乘
          if (Array.isArray(this.saveData.identityCardFront) && this.saveData.identityCardFront.length) {
            this.saveData.identityCardFront = this.saveData.identityCardFront[0];
          }
          if (Array.isArray(this.saveData.identityCardBack) && this.saveData.identityCardBack.length) {
            this.saveData.identityCardBack = this.saveData.identityCardBack[0];
          }
          delete this.saveData.drivingLicenceFront;
          delete this.saveData.drivingLicenceBack;
        }
        let res = {};
        this.saveData.driveSAt = new Date(this.saveData.driveSAt).getTime()
        this.saveData.driveEAt = new Date(this.saveData.driveEAt).getTime()

        this.saveLoading = true;
        if (this.type === 'add') {
          this.saveData.customerNo = this.customerNo;
          res = await addDriveManagementBq(this.saveData);
        }
        if (this.type === 'edit') {
          this.saveData.customerNo = this.customerNo;
          res = await editDriveManagement(this.recordId, this.saveData);
        }
        if (res.resultCode === 200) {
          this.saveLoading = false;
          this.closeDialog('refresh');
          this.$message.success('保存成功')
          this.fetchParams = { ...this.fetchParams };
        }
        this.saveLoading = false;
      }
    },
    closeDialog(param) {
      this.$emit('close', false, param);
    },
    resetFormList(data) {
      this.formList[0].initialValue = this.formList[0].initialValue == '20261002' ? this.typeItems[1].value : this.typeItems[0].value;
      //处理数据
      data.driverCard = data.potentialCustomerNo;
      const keys = Object.keys(data);
      this.formList.forEach(x => {
        if (keys.includes(x.fieldName)) {
          x.initialValue = data[x.fieldName];
        }
      });
      this.customerNo = data.customerNo;
    },
    closeHandler(val, data) {
      this.formList[0].initialValue = this.formList[0].initialValue == '20261002' ? this.typeItems[1].value : this.typeItems[0].value;
      this.visible = val;
      if (!data) return;
      this.resetFormList(data);
    },
    async getDriveCarList() {
      const res = await getDriveCarInfo();
      console.log('试驾车型', res);
      if (res.resultCode === 200) {
        let driveCarList = res.data.map(x => ({ value: x.testDriveId, text: x.carInfoName }));
        this.formList.find(x => x.fieldName === 'testDriveId').itemList.push(...driveCarList);
      }
    },
    async changeVinSelect(testDriveId) {
      const res = await getDriveCarInfo(testDriveId);
      if (res.resultCode === 200) {
        var self = res.data;
        self.map((item, index) => {
          if (item.testDriveId == testDriveId) {
            // this.formList.vin = Number(item.vin)
            this.formList.vin = item.vin;
            console.log('试驾vin', this.formList.vin);
            this.formList.forEach(x => {
              if (x.fieldName == 'vin') {
                x.initialValue = this.formList.vin;
              }
            });
          }
        });
      }
    },
    async getDriveWayList() {
      const res = await getDriveWayInfo();
      if (res.resultCode === 200) {
        let drivewaylist = res.data.map(x => ({ value: x.wayId, text: x.wayName }));
        // let oldList = [...this.formList.find(x => x.fieldName === 'wayId').itemList]
        // let newDrivewaylist = drivewaylist.filter(item => {
        //   return oldList[0].value !== item.value
        // })
        this.formList.find(x => x.fieldName === 'wayId').itemList.push(...drivewaylist);
      }
    },
    async openDriveCancel() {
      this.handleType = 'search';
      this.visible = true;
      this.showHandler();
    }
  }
};
</script>

<style lang="less" scoped></style>
